package impl

import (
	"context"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/repository/common/contract"
	"git.mycaigou.com/gfyx/micro-gfyx-bigdata-service/infrastructure/vars"
	"git.myscrm.cn/golang/stark/v4"
	"time"
)

/**
 * @Author: xiuliu
 * @Description:
 * @File:  sr_common_repo
 * @Version: 1.0.0
 * @Date: 2023/09/22 15:18
 */

type SrCommonRepo struct {
}

func NewSrCommonRepo() contract.SrCommonRepoIface {
	return &SrCommonRepo{}
}

func (s *SrCommonRepo) GetList(ctx context.Context, sql string) ([]map[string]interface{}, error) {
	db := vars.StarRocksDbConn.Get(ctx)

	results := make([]map[string]interface{}, 0)

	err := db.Raw(sql).Scan(&results).Error
	if err != nil {
		stark.Logger.Error(ctx, "SR查询错误：", err)
		return nil, err
	}

	formattedResults := make([]map[string]interface{}, len(results))
	for i, row := range results {
		formattedRow := make(map[string]interface{})
		for key, value := range row {
			if timestamp, ok := value.(time.Time); ok {
				formattedRow[key] = timestamp.Format("2006-01-02 15:04:05")
			} else {
				formattedRow[key] = value
			}
		}
		formattedResults[i] = formattedRow
	}

	return formattedResults, nil
}

func (s *SrCommonRepo) GetTotal(ctx context.Context, sql string) (int64, error) {
	var total int64
	db := vars.StarRocksDbConn.Get(ctx)

	results := map[string]interface{}{}
	err := db.Raw(sql).First(&results).Error
	if err != nil {
		stark.Logger.Error(ctx, "SR查询错误：", err)
		return 0, err
	}

	if value, ok := results["total"]; ok {
		if v, ok := value.(int64); ok {
			total = v
		}
	}
	return total, nil
}

func (s *SrCommonRepo) Save(ctx context.Context, sql string) (bool, error) {
	db := vars.StarRocksDbConn.Get(ctx)
	if res := db.Exec(sql); res.Error != nil {
		stark.Logger.Error(ctx, "SR执行错误：", res.Error)
		return false, res.Error
	}
	return true, nil
}
